<?php
/**
 * Descript
 * User: blue
 * Date: 2018/8/16 13:29
 */

namespace app\api\controller\v1;


use app\api\validate\RegisterValidate;
use app\lib\exception\ParamException;
use app\lib\exception\SuccessReturn;
use app\lib\face\Email;
use app\lib\serverLib\Security;
use think\Exception;
use think\facade\Request;

class ThirdUser
{

    public function regist(){
        $data=Request::except('id');
        //用户参数过滤和验证部分,1.不允许传入id,2.验证器验证规则
        // if(isset($data['id'])) unset($data['id']);
        (new RegisterValidate())->goCheck($data);
        //验证码比对
        $codeValid=$this->mailCodeValid();
        if(!$codeValid){
            throw new ParamException(['验证码不正确']);
        }
        //数据入库
        return  new SuccessReturn(['message'=>'用户注册成功']);

    }
    /**
     * 发送邮箱验证码
     * @return mixed
     * @throws Exception
     * @throws ParamException
     */
    public function registerMailCode(){
        $toEmail=Request::post('toMail');
        if(!$toEmail){
            throw new ParamException(['message'=>'请传入正确的邮箱号']);
        }
         $res=Security::makeRandon(6,true);
         if(!$res){
            throw new Exception();
         }
         $res=Email::sendEmail($toEmail,$res);
         if(!$res){
             throw new Exception(['message'=>'验证失败']);
         }
         if($res){
             session('randCode',$res);
             session('registMail',$toEmail);
             session('codeExpires',time());
         }

    }

    /**
     * 邮箱验证码比对函数
     * @return bool
     */
    private function mailCodeValid($data){
        if(empty($data['code'])) return false;
        $expires=config('send.mail_code_expires');
        if($data['code']==session('randCdode')&&$data['username']==session('registMail')&&$data['codeExpires']+$expires>time()){
            return true;
        }else{
            return false;
        }
    }
}